import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: Anastasia
 * Date: 23.01.15
 * Time: 9:44
 * To change this template use File | Settings | File Templates.
 */
public class LoaderDepartments extends JFrame implements ActionListener {        //сделать на сервере команду номер три


    private LoaderDepartments loaderDepartments;
    private ArrayList<Department>   departments;
    private  JPanel panel ;
    private JComboBox box;

    private JLabel label;
    private JLabel label2;

    private JButton editor;
    private JButton delete;
    private int index ;
    private JTable table;
    private JLabel label3;
    private JButton select;

    private JButton withoutChief;
    private JButton chieffromList;

    public LoaderDepartments()
    {
       departments = new ArrayList<Department>();
        index=-1;

    }



    public class Changer extends Thread implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {
                index =-1;

               // System.out.println(index);
                panel.remove(select);
                panel.remove(label3);


                withoutChief = new JButton("Без начальника");
                withoutChief.setBounds(5,100,200,30);
                panel.add(withoutChief);

         //       withoutChief.addActionListener(new WithoutChief());
                chieffromList = new JButton("Из списка");
                chieffromList.setBounds(215,100,200,30);
                panel.add(chieffromList);

            //    chieffromList.addActionListener(new GetterofEmployees());

                panel.add(chieffromList);
                panel.add(withoutChief);

                panel.repaint();
                panel.validate();

                // withoutDeparmentbutton = new JButton("Без отдела");
                // withoutDeparmentbutton.setBounds(200,250,200,30);
              //  panel.add(box);

                // withoutDeparmentbutton.addActionListener(new WithoutDepartment());     //добавление обработчика на кнопку без отдела


                // existDepartmentbutton = new JButton("Существуюший отдел");
                //  existDepartmentbutton.setBounds(410,250,200,30);

                //  existDepartmentbutton.addActionListener(new GetterofDepartment());   //вывод существующих отделов
                panel.validate();
                panel.repaint();

            }
            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }

    public class Selector extends Thread implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {

                index = box.getSelectedIndex();
                 System.out.println(index);
                panel.remove(box);

                label3 = new JLabel(departments.get(index).getInfo());
                label3.setBounds(20,100,300,50);

                panel.add(label3);

                select = new JButton("Изменить");
                select.setBounds(350,100,100,30);
                panel.add(select);
                select.addActionListener(new Changer());

                panel.repaint();
                panel.validate();


            }

            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }


    public class Edit  extends JFrame implements ActionListener{

        private Department department;

        private Department department2;

        private  Edit edit;

        private ArrayList<Employee> employees;
        private int anInt;


        private JLabel label;
        private JPanel panel;
        private JTextField name ;

        private JButton withoutChief;
        private JButton chieffromList;
        private JButton changer;
        private JLabel chief;

        private JComboBox list;
        private Employee employee;
        private JButton ok;
        //private JButton newEmployee;

        public Edit()
        {
            department = new Department();
            department2 = new Department();
            employees = new ArrayList<Employee>();
            anInt =-1;
        }

        public class Change extends Thread implements ActionListener
        {

            public void actionPerformed(ActionEvent arg0)
            {
                try
                {

                    anInt =-1;
                    panel.remove(select);
                    panel.remove(label3);

                    withoutChief = new JButton("Без начальника");
                    withoutChief.setBounds(5,100,200,30);
                    panel.add(withoutChief);

                    withoutChief.addActionListener(new WithoutChief());
                    chieffromList = new JButton("Из списка");
                    chieffromList.setBounds(215,100,200,30);
                    panel.add(chieffromList);

                    chieffromList.addActionListener(new GetterofEmployees());

                    panel.repaint();
                    panel.validate();

                }
                catch (Exception e)
                {
                    System.out.println("init error: " +e); // Print exception

                    e.printStackTrace();
                }



            }
        }


        public class Select extends Thread implements ActionListener     //обработчик на выбор сотрудника;
        {

            public void actionPerformed(ActionEvent arg0)
            {
                try
                {

                    anInt = list.getSelectedIndex();
                    //  System.out.print(anInt);

                    employee = employees.get(anInt);
                    label3 = new JLabel(employee.getName()+" "+employee.getLastName());
                    department2.setEmployee(employee);
                    select = new JButton("Изменить");
                   select.setBounds(300, 100, 200, 30);

                    select.addActionListener(new Change());
                    panel.add(select);
                    panel.remove(list);
                    label3.setBounds(50, 100, 200, 30);
                    panel.add(label3);
                    panel.repaint();
                    panel.validate();

                }
                catch (Exception e)
                {
                    System.out.println("init error: " +e); // Print exception

                    e.printStackTrace();
                }



            }
        }




        public class Sender extends Thread implements ActionListener
        {

            public void actionPerformed(ActionEvent arg0)
            {
                try
                {     String data = "1";

                    if(department2.getEmployee()!=null)

                    {
                        Employee employee1 = department2.getEmployee();

                        InetAddress addr = InetAddress.getByName(null);



                        Socket socket = new Socket(addr, 8080);

                        // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                        out.writeObject(new Exchanger(59,employee1));
                        //  System.out.println("Ok");

                        out.flush();  //чудный метод.


                        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                        Object object = in.readObject();


                       data = (String)object;

                    }



                    if(data.equals("1"))
                    {
                    department2.setName(name.getText());

                    InetAddress addr = InetAddress.getByName(null);


                     Object mas[] = new Object[2];
                        mas[0] = index;
                        mas[1] = department2;
                    Socket socket = new Socket(addr, 8080);

                    // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                    out.writeObject(new Exchanger(60,mas));
                    //  System.out.println("Ok");

                    out.flush();  //чудный метод.


                    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                    Object object = in.readObject();


                    String data1 = (String)object;

                    if (data1.equals("0"))
                    {


                        edit.dispose();
                        JOptionPane.showMessageDialog(null,"Cохранено", "OK",
                                JOptionPane.INFORMATION_MESSAGE);

                        edit.dispose();
                        loaderDepartments.dispose();

                    }
                    else{
                        if(data1.equals("1"))
                        {    JOptionPane.showMessageDialog(null,"Неверное название отдела", "Error",
                                JOptionPane.ERROR_MESSAGE);

                        }

                        if(data1.equals("2"))
                        {    JOptionPane.showMessageDialog(null,"Ошибка списка отделов", "Error",
                                JOptionPane.ERROR_MESSAGE);

                        }


                    }


               /*
                if(anInt!=-1)
                {
                    Object mas[] = new Object[2];
                    mas[0] = anInt;
                    mas[1] = department;

                    out.writeObject(new Exchanger(21,mas));
                    out.flush();


                }  */

                    out.close();
                    in.close();
                    socket.close();




                }

                    else
                    {
                        JOptionPane.showMessageDialog(null,"Невозмжно редакировать отдел,так как ссылка на начальника была изменена", "Error",
                                JOptionPane.ERROR_MESSAGE);
                        edit.dispose();
                    }

                }
                catch (Exception e)
                {
                    System.out.println("init error: " +e); // Print exception

                    e.printStackTrace();
                }



            }
        }


        public class WithoutChief extends Thread implements ActionListener
        {

            public void actionPerformed(ActionEvent arg0)
            {
                try
                {
                   anInt=-1;
                    //System.out.print(anInt);

                    department2.setEmployee(null);
                    panel.remove(chieffromList);
                    panel.remove(withoutChief);


                   select = new JButton("Изменить");
                    select.setBounds(300, 100, 200, 30);

                    select.addActionListener(new Change());
                    panel.add(select);
                    if(department.getEmployee()==null)
                    {
                       label3 = new JLabel("Отдел пока что без начальника");
                    }
                    else {
                        label3 = new JLabel(department.getEmployee().getLastName());}
                    panel.repaint();
                    label3.setBounds(50, 100, 200, 30);
                    panel.add(label3);
                    panel.repaint();
                    panel.validate();


                }

                catch (Exception e)
                {
                    System.out.println("init error: " +e); // Print exception

                    e.printStackTrace();
                }



            }
        }



        public class GetterofEmployees extends Thread implements ActionListener
        {

            public void actionPerformed(ActionEvent arg0)
            {
                try
                {
                    // JOptionPane.showMessageDialog(null,"Список отделов пуст", "Inane error",
                    // JOptionPane.ERROR_MESSAGE);




                    InetAddress addr = InetAddress.getByName(null);
                    Socket socket = new Socket(addr, 8080);

                    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                    out.writeObject(new Exchanger(31,null));
                    //  System.out.println("Ok");

                    out.flush();  //чудный метод.

                    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                    Object object = in.readObject();

                    employees = (ArrayList<Employee>)object;



                    if(employees == null||employees.size()==0)
                    {
                        JOptionPane.showMessageDialog(null,"Список сотрудников пуст", "Error",
                                JOptionPane.ERROR_MESSAGE);


                    }
                    else{


                        panel.remove(chieffromList);
                        panel.remove(withoutChief);
                        panel.repaint();


                        String info[]= new String[employees.size()];

                        for(int i =0;i< employees.size();i++)
                        {
                            info[i]=employees.get(i).getInfo();
                        }
                        list = new JComboBox(info);

                        list.addActionListener(new Select());
                        list.setBounds(50,150,100,50);
                        list.setVisible(true);
                        panel.add(list);
                        panel.repaint();
                        panel.validate();

                    }

                }

                catch (Exception e)
                {
                    System.out.println("init error: " +e); // Print exception

                    e.printStackTrace();
                }



            }
        }


        public void actionPerformed(ActionEvent arg0)
        {

          /* try{
          InetAddress addr = InetAddress.getByName(null);

            Socket socket = new Socket(addr, 8080);

            //         BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter outer = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())), true);
            outer.println(3);  //это будет команда


            socket.close();  }

        catch(UnknownHostException e)
        {

        }

        catch(IOException e)
        {

        }         */


           if(index == -1)
           {  JOptionPane.showMessageDialog(null,"Не выбран  отдел", "Error",
                   JOptionPane.ERROR_MESSAGE);
               System.out.println(anInt);

           }

            else
           {

               try{

                   department = departments.get(index);  //из старого списка

                   department2 = department;


                   Exchanger exchanger = new Exchanger(index,department);
                   InetAddress addr = InetAddress.getByName(null);



                   Socket socket = new Socket(addr, 8080);

                   // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                   ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                   out.writeObject(new Exchanger(57,exchanger));
                   //  System.out.println("Ok");

                   out.flush();  //чудный метод.


                   ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                   Object object = in.readObject();

                   String string = (String)object;





                   if(string.equals("1"))
                   {



                       edit = new Edit();
            edit.setVisible(true);
            edit.setBounds(100, 200, 500, 500);
            panel = new JPanel();
            panel.setLayout(null);




            label = new JLabel("Название отдела");
            label.setBounds(20,10,150,30);
            panel.add(label) ;

            name = new JTextField();
            name.setBounds(220, 10, 200, 30);
             name.setText(department.getName());

            panel.add(name);

            if(department.getEmployee()!=null)
            {
            label3 = new JLabel(department.getEmployee().getInfo()) ;

                label3.setBounds(50,100,100,30);
                panel.add(label3);
            }

                   else
            { label3 = new JLabel("Отдел без начальника") ;

                label3.setBounds(50,100,100,30);
                panel.add(label3);}
           /* withoutChief = new JButton("Без начальника");
            withoutChief.setBounds(5,100,200,30);
            panel.add(withoutChief);

            withoutChief.addActionListener(new WithoutChief());
            chieffromList = new JButton("Из списка");
            chieffromList.setBounds(215,100,200,30);
            panel.add(chieffromList);

            chieffromList.addActionListener(new GetterofEmployees()); */

            select = new JButton("Изменить");
                   select.setBounds(200,100,80,30);
                   panel.add(select);
                       select.addActionListener(new Change());


            ok = new JButton("Сохранить изменения");
            ok.setBounds(200, 150, 200, 30);
            panel.add(ok);
            ok.addActionListener(new Sender());


            //  newEmployee = new JButton("Новый начальник");
            //    newEmployee.setBounds(430,100,200,30);
            //  panel.add(newEmployee);

            // newEmployee.addActionListener(new AddChief());





            edit.add(panel);

                       panel.validate();
                       panel.repaint();
            edit.setPreferredSize(new Dimension(500, 800));

               }


                   else
                   {
                       JOptionPane.showMessageDialog(null,"Невозмжно редакировать отдел, так как он был изменен или удален", "Error",
                               JOptionPane.ERROR_MESSAGE);

                       loaderDepartments.dispose();

                   }



               }
               catch (Exception e)
               {
                   System.out.println("init error: " +e); // Print exception

                   e.printStackTrace();
               }




        }
    }
    }


    public class Changer1 extends Thread implements ActionListener
    {

        public void actionPerformed(ActionEvent arg0)
        {
            try
            {
                index =-1;


                InetAddress addr = InetAddress.getByName(null);



                Socket socket = new Socket(addr, 8080);

                // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
                out.writeObject(new Exchanger(12,null));
                //  System.out.println("Ok");

                out.flush();  //чудный метод.


                ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
                Object object = in.readObject();

                departments = (ArrayList<Department>)object;


                if(departments == null||departments.size()==0)
                {
                    JOptionPane.showMessageDialog(null,"Список отделов пуст", "Error",
                            JOptionPane.ERROR_MESSAGE);


                    loaderDepartments.dispose();


                }
                else{



                    String columnsnames[]= {"Hазвание отдела", "Начальник", };
                    String info1 [][] = new String [departments.size()][] ;

                    for (int i =0;i<departments.size();i++)
                    {
                        info1[i] = new String[2];
                        info1[i][0] = departments.get(i).getName();


                        if(departments.get(i).getEmployee()==null)
                        {
                            info1[i][1] = "отдел без начальника";

                        }
                        else
                        {
                            info1[i][1] = departments.get(i).getEmployee().getName()+ " "+departments.get(i).getEmployee().getSurname()+" "+ departments.get(i).getEmployee().getLastName();

                        }



                    }

                    table = new JTable(info1, columnsnames);
                    table.setBounds(10,100,500,200);
                    JScrollPane scrollPane = new JScrollPane(table);

                    scrollPane.setViewportView(table);
                    scrollPane.setVisible(true);


                    panel.add(scrollPane);

                    //  scrollPane.getViewport().add(table);

                    table.setBounds(50, 100, 300, 200);

                    ListSelectionModel selModel = table.getSelectionModel();

                    selModel.addListSelectionListener(new SelectorTable());

                    panel.add(table);

                    panel.remove(select);
                    panel.remove(label3);

                    panel.add(table);


                    panel.validate();
                    panel.repaint();
                }

            }
            catch (Exception e)
            {
                System.out.println("init error: " +e); // Print exception

                e.printStackTrace();
            }



        }
    }

    public class SelectorTable extends Thread implements ListSelectionListener
    {

        public void valueChanged(ListSelectionEvent e)
        {
            try
            {

                index = table.getSelectedRow();

                panel.remove(table);

                label3 = new JLabel(departments.get(index).getInfo());
                label3.setBounds(20,100,300,50);

                panel.add(label3);

                select = new JButton("Изменить");
                select.setBounds(350,100,100,30);
                panel.add(select);
                select.addActionListener(new Changer1());

                panel.repaint();
                panel.validate();


            }

            catch (Exception exc)
            {
                System.out.println("init error: " +exc); // Print exception

                exc.printStackTrace();
            }



        }
    }



    public void actionPerformed(ActionEvent arg0)
    {
        try{




            InetAddress addr = InetAddress.getByName(null);



            Socket socket = new Socket(addr, 8080);

            // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
            out.writeObject(new Exchanger(12,null));
            //  System.out.println("Ok");

            out.flush();  //чудный метод.


            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
            Object object = in.readObject();

            departments = (ArrayList<Department>)object;


            if(departments == null||departments.size()==0)
            {
                JOptionPane.showMessageDialog(null,"Список отделов пуст", "Error",
                        JOptionPane.ERROR_MESSAGE);


            }
            else{
                loaderDepartments = new LoaderDepartments();

                panel = new JPanel() ;
                panel.setLayout(null);
                loaderDepartments.setVisible(true);
                loaderDepartments.setBounds(100, 100, 500, 500) ;

                String columnsnames[]= {"Hазвание отдела", "Начальник", };
                String info1 [][] = new String [departments.size()][] ;

                for (int i =0;i<departments.size();i++)
                {
                    info1[i] = new String[2];
                    info1[i][0] = departments.get(i).getName();


                    if(departments.get(i).getEmployee()==null)
                    {
                        info1[i][1] = "отдел без начальника";

                    }
                    else
                    {
                        info1[i][1] = departments.get(i).getEmployee().getName()+ " "+departments.get(i).getEmployee().getSurname()+" "+ departments.get(i).getEmployee().getLastName();

                    }



                }

                table = new JTable(info1, columnsnames);
                table.setBounds(10,100,500,200);
                JScrollPane scrollPane = new JScrollPane(table);

                scrollPane.setViewportView(table);
                scrollPane.setVisible(true);


                panel.add(scrollPane);

                //  scrollPane.getViewport().add(table);

                table.setBounds(50,100,300,200);

                ListSelectionModel selModel = table.getSelectionModel();

                selModel.addListSelectionListener(new SelectorTable());

                panel.add(table);

                label = new JLabel("Список отделов:");
                label.setBounds(10,50,200,30);
                panel.add(label);

                label2 = new JLabel("Выберите отдел для действия с ним") ;
                label2.setBounds(150,50,250,30);
                panel.add(label2);




                editor = new JButton("Редактировть запись");
                editor.setBounds(30,320,150,30);
                panel.add(editor);

                editor.addActionListener(new Edit());


               // editor.addActionListener(new Edit());
                delete = new JButton("Удалить запись");
                delete.setBounds(250, 320, 150, 30);
                panel.add(delete);


               // panel.add(box);
                panel.repaint();
                panel.validate();
                loaderDepartments.add(panel);
                // loaderDepartments.setPreferredSize(new Dimension(500, 800));
            }





        }
        catch (Exception e)
        {
            System.out.println("init error: " +e); // Print exception

            e.printStackTrace();
        }
    }
}






